<?php

namespace app\common\model;

use app\common\model\order\Order;
use think\Model;

/**
 * 会员余额日志模型
 */
class MoneyLog extends Model
{

    // 表名
    protected $name = 'user_money_log';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = '';
    // 追加属性
    protected $append = [
        'money_text',
        'createtime_text',
    ];
    public function getCreatetimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['createtime']) ? $data['createtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }
    public function getTypeList()
    {
        return ['1' => __('支出'), '2' => __('收入')];
    }
    public function getMoneyTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['source_type']) ? $data['source_type'] : '');
        $list = $this->getMoneyType();
        return isset($list[$value]) ? $list[$value] : '';
    }
    public static function getMoneyType()
    {
        return [
            100 => '销售提成',
            101 => '订单结算代理回馈收益',
            200 => '管理提成',
            300 => '伯乐津贴',
            400 => '订单结算分红奖收益',
            500 => '余额转赠',
            501 => '余额获赠',
            502 => '余额提现',
            503 => '余额支付（不可提现余额）',
            504 => '余额支付（可提现余额）',
            600 => '管理员变更金额',
        ];
    }
    /**
     * Notes:记录会员账户流水，如果变动类型是成长值，且是增加的，则调用更新会员等级方法。该方法应在添加用户账户后调用
     * @author: cjh 2020/12/15 11:49
     * @param int $user_id  用户id
     * @param float $amount 变动数量
     * @param int $change_type  变动类型：1-减少；2-增加
     * @param int $source_type 来源类型
     * @param string $source_id 来源id
     * @param string $source_sn 来源单号
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function income($user_id, $amount, $change_type, $source_type, $source_sn = '')
    {
        $user = new User;
        $user = $user->get($user_id);
        if (empty($user)) {
            return false;
        }
        $before = bcadd($user->money, $user->no_money, 2);
        if ($change_type == 1) {
            if ($source_type == 503) {
                $user->setDec('no_money', $amount);
            } else {
                $user->setDec('money', $amount);
            }
            $amount = -$amount;
        } else {
            if ($source_type == 500) {
                $user->setInc('no_money', $amount);
            } else {
                $user->setInc('money', $amount);
            }
        }
        $list =  self::getMoneyType();
        $left_amount = bcadd($user->money, $user->no_money, 2);
        $account_log = new self;
        $data['type'] = $change_type;
        $data['order_sn'] = $source_sn;
        $data['user_id'] = $user_id;
        $data['money'] = $amount ?? 0;
        $data['before'] = $before ?? 0;
        $data['after'] = $left_amount ?? 0;
        $data['memo'] = isset($list[$source_type]) ? $list[$source_type] : '';
        $data['source_type'] = $source_type;
        $account_log->allowField(true)->save($data);
        return true;
    }


    //订单分佣
    public static function subcommission($pay_money, $uid, $order_sn)
    {
        $user = User::get($uid);
        if ($user->level > 0) {
            return true;
        }
        $order = Order::get(['sn' => $order_sn]);
        //直推分佣
        if ($user->paren_ids && $order->state =='1') {
            //分佣比例
            $proportion = array(1 => 0, 2 => 0.2, 3 => 0.25, 4 => 0.3);
            $users = User::whereIn('id', $user->paren_ids)->orderRaw("field(id, $user->paren_ids)")->select();
            $por = 0;
            foreach ($users as $k => $v) {
                if ($v->group_id > $user->group_id) {
                    if ($proportion[$v->group_id] > 0) {
                        $proportion[$v->group_id] -= $por;
                        if ($proportion[$v->group_id] > 0) {
                            $money = bcmul($pay_money,  $proportion[$v->group_id], 2);
                            if ($money > 0) {
                                self::income($v->id, $money, 2, 100, $order_sn);
                            }
                            $por += $proportion[$v->group_id];
                        }
                    }
                }
            }
        }
        // //代理回馈收益
        // $userGroup = User::where('group_id', '>', 1)->where('id', '<>', $uid)->limit(2000)->order('grouptime asc')->select();
        // foreach ($userGroup as $v) {
        //     if ($v->group_id == 2) {
        //         $feedbackMoney = bcmul(bcmul($pay_money, 0.1, 2), 2 / 30, 2);
        //     }
        //     if ($v->group_id == 3) {
        //         $feedbackMoney = bcmul(bcmul($pay_money, 0.1, 2), 8 / 30, 2);
        //     }
        //     if ($v->group_id == 4) {
        //         $feedbackMoney = bcmul(bcmul($pay_money, 0.1, 2), 20 / 30, 2);
        //     }
        //     self::income($v->id, $feedbackMoney, 2, 101, $order_sn);
        // }

        //管理收益
        if ($user->paren_ids) {
            $management = User::whereIn('id', $user->paren_ids)->orderRaw("field(id, $user->paren_ids)")->where('level', '>', 0)->select();
            $lv = array(1 => 0.05, 2 => 0.09, 3 => 0.12, 4 => 0.15, 5 => 0.19, 6 => 0.21);
            $por = 0;
            foreach ($management as $key => $v) {
                if ($v->level > $user->level) {
                    if ($lv[$v->level] > 0) {
                        $lv[$v->level] -= $por;
                        if ($lv[$v->level] > 0) {
                            $managementMoney = bcmul($pay_money,  $lv[$v->level], 2);
                            if ($managementMoney > 0) {
                                self::income($v->id, $managementMoney, 2, 200, $order_sn);
                            }
                            $por += $lv[$v->level];
                        }
                    }
                }
                //伯乐奖
                if ($v->pid) {
                    $bole = User::get($v->pid);
                    $boleMoney = bcmul($managementMoney, 0.25, 2);
                    self::income($bole->id, $boleMoney, 2, 300, $order_sn);
                }
            }
        }
    }
    //总裁分红
    public static function dividend()
    {
        $count = self::whereTime('createtime', 'between', [date('Y-12-31'), date('Y-12-31 23:59:59')])->count();
        if ($count) {
            exception('今年已分红');
        }
        $user = User::all(['level' => 7]);
        $totalMoney = Order::where('status', '>', '0')->whereTime('paytime', 'years')->sum('pay_money');
        foreach ($user as $v) {
            $dividendMoney = bcmul($totalMoney, 0.02, 2);
            $uids = User::where("find_in_set({$v->id},paren_ids)")->column('id');
            $sumMoney = Order::where('status', '>', '0')->whereTime('paytime', 'years')->whereIn('id', $uids)->sum('pay_money');
            self::income($v->id, bcmul($dividendMoney, bcdiv($sumMoney, $totalMoney, 2), 2), 2, 400);
        }
    }
}
